/**
 * Created by liuqingxia on 2016/4/11.
 */


/**
 * 点击数据源选择的插入按钮
 */
function clickSourceInsertBtn(selectDiv,type) {

    $(document).on("click", "." + type, function () {

        var dataSource = $.trim($(this).parent().find("span.dataSource").html());
        var selectDivId = $.trim($(this).parent().parent().attr("id"));
        var selectDataTableName=$.trim($(this).siblings(".dataSource").find("input[name=dataTableName]").val());
        var selectDataSourceId=$.trim($(this).siblings(".dataSource").find("input[name=tdbid]").val());
        var selectDataSourceJdbc=$.trim($(this).siblings(".dataSource").find("input[name=tdbjdbcurl]").val());
        var selectDataSourceIP=selectDataSourceJdbc.split(":")[0];
        var selectDataSourcePort=selectDataSourceJdbc.split(":")[1];
       
        var dataSourceHtml = "" +
            "<span class='dataSource-row' style='overflow: hidden'>" +
                "<button class='removeBtn datasource-use-btn'>删除</button>" +
                "<span class='dataSource'>" + "&nbsp;" +
                    dataSource +
                "</span>" +
                "<span class='choiceDbPort'><input type='hidden' name='choiceDbPort' value='"+selectDataSourcePort+"' /></span>"+
                "<span class='choiceDbIp'><input type='hidden' name='choiceDbIp' value='"+selectDataSourceIP+"' /></span>"+
                "<span class='choiceDataTableName'><input type='hidden' name='dbname' value='"+selectDataTableName+"' /></span>"+
                "<span class='choiceDataTableId'><input type='hidden' name='dbid' value='"+selectDataSourceId+"' /></span>"+
                "<span class='choiceDataTableJdbcUrl'><input type='hidden' name='dbJdbcUrl' value='"+selectDataSourceJdbc+"' /></span>"+
                "<span >读权重：<input style='width:40px;' name='readWeight' type='number' value='0' min='0'/></span>"+
                "<span >写权重：<input style='width:40px;' name='writeWeight' type='number' value='0' min='0'/></span>"+
            "</span>";
        $("#"+ selectDiv).css("width","auto");
        $("#" + selectDiv).append(dataSourceHtml);
    });
} 
function clickBackSourceInsertBtn(selectDiv,type) {

    $(document).on("click", "." + type, function () {

        var dataSource = $.trim($(this).parent().find("span.dataSource").html());
        var selectDivId = $.trim($(this).parent().parent().attr("id"));
        var selectDataTableName=$.trim($(this).siblings(".dataSource").find("input[name=dataTableName]").val());
        var selectDataSourceId=$.trim($(this).siblings(".dataSource").find("input[name=tdbid]").val());
        var selectDataSourceJdbc=$.trim($(this).siblings(".dataSource").find("input[name=tdbjdbcurl]").val());
        var selectDataSourceIP=selectDataSourceJdbc.split(":")[0];
        var selectDataSourcePort=selectDataSourceJdbc.split(":")[1];
       
        var dataSourceHtml = "" +
            "<span class='dataSource-row' style='overflow: hidden'>" +
                "<button class='removeBtn datasource-use-btn'>删除</button>" +
                "<span class='dataSource'>" + "&nbsp;" +
                    dataSource +
                "</span>" +
                "<span class='choiceDbPort'><input type='hidden' name='choiceDbPort' value='"+selectDataSourcePort+"' /></span>"+
                "<span class='choiceDbIp'><input type='hidden' name='choiceDbIp' value='"+selectDataSourceIP+"' /></span>"+
                "<span class='choiceDataTableName'><input type='hidden' name='dbname' value='"+selectDataTableName+"' /></span>"+
                "<span class='choiceDataTableId'><input type='hidden' name='dbid' value='"+selectDataSourceId+"' /></span>"+
                "<span class='choiceDataTableJdbcUrl'><input type='hidden' name='dbJdbcUrl' value='"+selectDataSourceJdbc+"' /></span>"+
            "</span>";
        $("#"+ selectDiv).css("width","auto");
        $("#" + selectDiv).append(dataSourceHtml);
    });
}

/**
 * 点击数据源选择的删除按钮
 */
function clickSourceRemoveBtn() {
    $(document).on("click", ".removeBtn", function () {
        $(this).parent().remove();
    });
}

/**
 * 闭包，allDataSourceDiv
 * @param divId
 * @param findAllUrl
 * @returns {{init: init, getAllDataSources: getAllDataSources}}
 */
function getAllDataSourceDiv(divId, findAllUrl,type) {

    var divId = divId;
    var findAllUrl = findAllUrl;

    /**
     * 获取所有的数据源列表
     * @returns {Array}
     */
    function getAllDataSources() {
        var dataSources = [];
        var url = getUrlBySuffix(findAllUrl);
        try {
            $.postHttpSync({}, url, function (json) {
                if (json && json.success) {
                    dataSources = json['list'];
                } else {
                    console.error("获取数据源数组失败");
                }
            });
        } catch (e) {
            console.error("获取数据源数组失败，" + e.message);
        }
        return dataSources;
    }

    /**
     * 将dataSource数组与html渲染
     * @param dataSources
     * @returns {Array}
     */
    function getDataSourceHtml(dataSources,type) {
        var dataSourceHtml = [];
        for (var i = 0; i < dataSources.length; i++) {
            var dataSource = dataSources[i];
            var dataSourceType=dataSource["sourceType"];
            if(!(dataSourceType=="4")){
            	var dataSourceRow = "" +
                "<span class='dataSource-row'>" +
                    "<button class='insertBtn " + type +" datasource-use-btn'>添加</button>" +
                    "<span class='dataSource'>" +
                    "<span class='dataSourceId'>" +
                        dataSource['id'] +
                    "</span>" + "&nbsp;" +
                        dataSourceName(dataSource['userName'], dataSource['jdbcUrl']) +
                        "<span class='dataTabelName'>" +
                        "<input type='hidden' name='dataTableName' value='"+ getDataBaseName(dataSource['jdbcUrl'])+"' />" +
                        "</span>"+
                        "<span class='tdbid'>" +
                        "<input type='hidden' name='tdbid' value='"+ (dataSource['id'])+"' />" +
                        "</span>"+
                        "<span class='tdbjdbcurl'>" +
                        "<input type='hidden' name='tdbjdbcurl' value='"+ (getJdbc(dataSource['jdbcUrl']))+"' />" +
                        "</span>"+
                    "</span>" +
                "</span>";
           
            dataSourceHtml.push(dataSourceRow);
            }
            
        }
        return dataSourceHtml;
    }

    function getDataBaseName(dataSourcesUrl){
    	var jdbcUrl=dataSourcesUrl;
    	if (jdbcUrl.contains("DESCRIPTION")) {/*oracle的RAC格式*/
            return dataBaseNameFliter(HandleOracleRACName(jdbcUrl));
        }

        var removeQuestMark = jdbcUrl.split("?")[0];
        if (!containsIP(removeQuestMark) && removeQuestMark.contains("@")) {
            //console.log("@===="+dataBaseUrlFliter(removeQuestMark.split("@")[1]));
            return dataBaseNameFliter(removeQuestMark.split("@")[1]);
        }

        if (!containsIP(removeQuestMark) && removeQuestMark.contains("mysql://")) {
            //console.log("mysql===="+removeQuestMark.split("mysql://")[1]);
            return dataBaseNameFliter(removeQuestMark.split("mysql://")[1]);
        }
        
        var ipPortDbReg = /\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}:\d{1,6}(\/|\:)\w+/;
        
        var ipPortDb = $.trim(ipPortDbReg.exec(removeQuestMark)).split(",")[0];
        return dataBaseNameFliter(ipPortDb);
    }
    
    
    function dataBaseNameFliter(ipPortDBName){
    	if(ipPortDBName.contains("/")){
    		return ipPortDBName.split("/")[1];
    	}else{
    		var ipPortDBNames=ipPortDBName.split(":");
    		return ipPortDBName.split(":")[(ipPortDBNames.length-1)];
    	}
    }
    
    function getJdbc(dataSourcesUrl){
    	var jdbcUrl=dataSourcesUrl;
    	if (jdbcUrl.contains("DESCRIPTION")) {/*oracle的RAC格式*/
            return dataBaseUrlFliter(HandleOracleRACName(jdbcUrl));
        }

        var removeQuestMark = jdbcUrl.split("?")[0];
        if (!containsIP(removeQuestMark) && removeQuestMark.contains("@")) {
            //console.log("@===="+dataBaseUrlFliter(removeQuestMark.split("@")[1]));
            return dataBaseUrlFliter(removeQuestMark.split("@")[1]);
        }

        if (!containsIP(removeQuestMark) && removeQuestMark.contains("mysql://")) {
            //console.log("mysql===="+removeQuestMark.split("mysql://")[1]);
            return dataBaseUrlFliter(removeQuestMark.split("mysql://")[1]);
        }
        
        var ipPortDbReg = /\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}:\d{1,6}(\/|\:)\w+/;
        
        var ipPortDb = $.trim(ipPortDbReg.exec(removeQuestMark)).split(",")[0];
        return dataBaseUrlFliter(ipPortDb);
    }
    function dataBaseUrlFliter(ipPortDBName){
    	if(ipPortDBName.contains("/")){
    		return ipPortDBName.split("/")[0];
    	}else{
    		return ipPortDBName.substring(0,ipPortDBName.lastIndexOf(":"));
    	}
    }
    
    /**
     * 初始化allDataSourceDiv
     */
    function init() {
        var dataSources = getAllDataSources();
        var dataSourceHtml = getDataSourceHtml(dataSources,type);
        var allDataSourceDiv = $("#" + divId);
        allDataSourceDiv.empty();
        for (var i in dataSourceHtml) {
            allDataSourceDiv.append(dataSourceHtml[i]);
        }
    }

    return {
        init: init,
        getAllDataSources: getAllDataSources
    };

}

